package com.example.amtf_tmdrecycle;

import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class ProjectAdapter extends RecyclerView.Adapter<ProjectAdapter.ViewHolder>  implements ItemTouchHelperCallback.ItemTouchHelperAdapter {
    private List<Todolistinfo> mProjectList;                                            //存储peoject的信息
    private OnItemClickLitener   mOnItemClickLitener;                                            //利用回调实现item点击
    private MyDatabaseHelper dbHelper;                                                  //删除数据库中的信息
    private SQLiteDatabase db;
    //设置回调接口
    public interface OnItemClickLitener{
        void onItemClick(View view, int position);
    }

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener){
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //用来创建ViewHolder实例，再将加载好的布局传入构造函数，最后返回ViewHolder实例
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.project_item,null);
        final ViewHolder holder=new ViewHolder(view);

        holder.finish_btn.setOnClickListener(new View.OnClickListener() {       //当控件被点击时 实现删除功能
            @Override
            public void onClick(View v) {
                db.delete("TodoList","project=?",new String[]{mProjectList.get(holder.getAdapterPosition()).getName()});
                if(mProjectList.isEmpty()) {
                    db.close();
                }
                mProjectList.remove(holder.getAdapterPosition());
                notifyItemRemoved(holder.getAdapterPosition());
            }
        });
        return holder;
    }
    public ProjectAdapter(List<Todolistinfo> projecList){                               //构造函数初始化mProject
        mProjectList=projecList;
        dbHelper =new MyDatabaseHelper(MyApplication.getContext(),"TodoList.db",null,1);
        dbHelper.getWritableDatabase();
        db=dbHelper.getWritableDatabase();
    }

    public void update(List<Todolistinfo> list){                            //数据改变时将新的list传入控件
        this.mProjectList=list;
        notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        //用于对RecyclerView的子项进行赋值，会在每个子项滚动到屏幕内的时候执行
        Todolistinfo todoProject=mProjectList.get(position);
        holder.projectName.setText(todoProject.getName());
        holder.projectTime.setText(todoProject.getTime());
        holder.projectTime_end.setText(todoProject.getEnd_time());
        holder.projectTime_end.setTextColor(Color.GRAY);
        holder.projectProgress.setProgress(todoProject.getProgress());
        holder.textofProgress.setText(""+todoProject.getProgress()+"%");
        byte[] imageData=todoProject.getImage();

        //将日期转为毫秒数
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date end_date = new Date();
        try {
            end_date = simpleDateFormat.parse(todoProject.getEnd_time());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(end_date.getTime()<System.currentTimeMillis()){
            holder.projectName.setTextColor(Color.RED);
        }


        if (imageData!=null) {
            //将字节数组转化为位图
            Bitmap imagebitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
            //将位图显示为图片
            holder.projectImage.setImageBitmap(imagebitmap);
        }else {
            holder.projectImage.setBackgroundResource(android.R.drawable.menuitem_background);
        }

        holder.itemView.setOnClickListener(new View.OnClickListener(){          //实现item被点击跳转
            @Override
            public void onClick(View v) {
                mOnItemClickLitener.onItemClick(v, position);
            }
        });
    }

    @Override
    public int getItemCount() {                 //得到当前list中item的数目
        return mProjectList.size();
    }

    @Override
    public void onMove(int fromPosition, int toPosition) {
        /**
         * 在这里进行给原数组数据的移动
         */
        Collections.swap(mProjectList, fromPosition, toPosition);
        /**
         * 通知数据移动
         */
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public void onSwipe(int position) {
        /**
         * 原数据移除数据
         * 包括数据库中的
         */

        db.delete("TodoList","project=?",new String[]{mProjectList.get(position).getName()});
        if(mProjectList.isEmpty()) {
            db.close();
        }
        mProjectList.remove(position);

        /**
         * 通知移除
         */
        notifyItemRemoved(position);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{         //绑定item中的控件
        View todoView;            //监听相关：用来保存RecyclerView的子项最外层的实例
        TextView projectName;
        TextView projectTime;
        TextView projectTime_end;
        Button finish_btn;
        ProgressBar projectProgress;
        TextView textofProgress;
        ImageView projectImage;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            todoView=itemView;  //监听相关：赋值
            projectName=itemView.findViewById(R.id.project_list_item);
            projectTime=itemView.findViewById(R.id.time_list_item);
            finish_btn=itemView.findViewById(R.id.finish_list_item);
            projectProgress=itemView.findViewById(R.id.progressBar);
            textofProgress=itemView.findViewById(R.id.progressBar_text);
            projectTime_end=itemView.findViewById(R.id.end_time_list_item);
            projectImage=itemView.findViewById(R.id.image_item);
        }
    }
}
